<template>
	<el-dialog :visible.sync="dialogVisible" title="订单收付款记录" width="1200px" :append-to-body="false" v-drag2anywhere
		:close-on-click-modal="false">
		<!--顶部基本信息-->
		<el-form label-width="85px" :model="data">
			<el-row :gutter="20">
				<el-col :span="6">
					<el-form-item label="外部单号:">{{data.ordercode}} </el-form-item>
				</el-col>
        <el-col :span="6">
        	<el-form-item label="内部单号:">{{data.ouid}} </el-form-item>
        </el-col>
				<el-col :span="6">
					<el-form-item label="下单渠道:">{{data.platform}}---[折扣:{{data.platformrate*100}}%]</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="订单总额:">{{format2Number(data.sum_order,numdigits)}}</el-form-item>
				</el-col>
        <el-col :span="6">
        	<el-form-item label="应收金额:" ><span>{{format2Number(data.sum_platform,numdigits)}}</span> 元</el-form-item>
        </el-col>
        <el-col :span="6">
        	<el-form-item label="已收金额:"><span>{{format2Number(data.income_rmb,numdigits)}}</span> 元</el-form-item>
        </el-col>
        <el-col :span="6">
        	<el-form-item label="应付金额:"><span>{{format2Number(data.sum_sup,numdigits)}}</span> 元</el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="合作商">
            {{data.supname}}
          </el-form-item>
        </el-col>
			</el-row>
		</el-form>

		<el-form label-width="90px">
			<el-row>
				<el-col>
					<el-form-item label="收款记录:" label-width="90px">
            <el-row>
              <div style="display: flex;">
                <div style="flex: 1;"></div>
                <div>
                  <el-button type="primary" size="mini" :disabled="data.income_status=='1'" @click="handleShowNewGetUI">新增收款</el-button>
                </div>
              </div>
            </el-row>
						<el-row>
              <el-col>
                 <el-row>
                   <el-col :span="20"></el-col>
                   <el-col :span="4" style="text-align: right;">
                   </el-col>
                 </el-row>
              </el-col>
							<el-col>
								<el-table :data="getlist" border empty-text="暂无收款记录">
									<el-table-column type="index" label="序号" align="center"></el-table-column>
									<el-table-column prop="date" label="收款日期" width="150px"> </el-table-column>
                  <el-table-column prop="platform" label="来款单位" width="150px"> </el-table-column>
									<el-table-column prop="amount" label="金额" width="100px" align="center">
										<template v-slot="scope">
											{{format2Number(scope.row.amount,2)}}
										</template>
									</el-table-column>
									<el-table-column prop="memo" label="备注"></el-table-column>
									<el-table-column label="操作" align="center" width="100px">
										<template v-slot="scope">
											<el-popconfirm title="确定要删除此收款记录吗？"
												@confirm="handle_delete_get(scope.$index,scope.row)">
												<el-button type="danger" slot="reference" icon="el-icon-delete" circle></el-button>
											</el-popconfirm>
										</template>
									</el-table-column>
								</el-table>
								<div style="text-align: right; height: 30px; border: 1px solid #EEEEEE; padding:5px 10px; border-top: none;">
									<span>已收总额: {{format2Number(data.income_rmb,2)}}</span>
								</div>
							</el-col>
						</el-row>
						</div>
					</el-form-item>
				</el-col>
				<el-col>
					<el-form-item label="付款记录:">
						<el-row>
							<el-col>
								<el-row>
									<el-col :span="5">
										<el-form-item label="应付总额:" label-width="80px">{{data.sum_sup}}</el-form-item>
									</el-col>
									<el-col :span="5">
										<el-form-item label="合作折扣:" label-width="80px">{{(data.suprate*100)}}%</el-form-item>
									</el-col>
									<el-col :span="5">
										<el-form-item label="已付金额:" label-width="80px">{{format2Number(data.paid_rmb,numdigits)}} 元</el-form-item>
									</el-col>
									<el-col :span="5">
										<el-form-item label="未付金额:" label-width="80px"><span>{{format2Number(data.sum_sup-data.paid_rmb,numdigits)}}</span> 元</el-form-item>
									</el-col>
									<el-col :span="4" style="text-align: right;">
										<el-button type="primary" size="mini" :disabled="data.paid_status==1" @click="handleShowNewPayUI">新增付款</el-button>
									</el-col>
								</el-row>
							</el-col>
						</el-row>


						<div style="border: 1px solid #EEEEEE; border-radius: 5px;">
							<div style=" margin: 5px; display: flex;">
								<div style="flex:1">
									<div>
										<span style="margin-left: 10px;">是否结清:</span>
										<el-switch v-model="paidstatus"  active-color="#13ce66" inactive-color="#ff4949"  @change="handleSwitchPaidStatus"></el-switch>
									</div>
								</div>
							</div>
						</div>
						<el-table :data="paylist" border empty-text="暂无收款记录">
							<el-table-column type="index" label="序号" align="center"></el-table-column>
							<el-table-column prop="date" label="付款日期" width="140px"> </el-table-column>
              <el-table-column prop="paytype" label="付款方式" width="100px" align="center"></el-table-column>
							<el-table-column prop="cktitle" label="收款账号"  show-overflow-tooltip>
							</el-table-column>
              <el-table-column prop="amount" label="金额" width="100px" align="center"></el-table-column>
 							<el-table-column prop="memo" label="备注"></el-table-column>
							<el-table-column label="操作" align="center" width="90px">
								<template v-slot="scope">
									<el-popconfirm title="确定要删除此付款记录吗？"
										@confirm="handle_delete_pay(scope.$index,scope.row)">
										<el-button type="danger" slot="reference" icon="el-icon-delete" circle></el-button>
									</el-popconfirm>
								</template>
							</el-table-column>
						</el-table>
						<div
							style="text-align: right; height: 30px; border: 1px solid #EEEEEE; padding:5px 10px; border-top: none;">
							<span>已付总额: {{format2Number(data.paid_rmb,numdigits)}}</span>
						</div>
						</div>
					</el-form-item>
				</el-col>
			</el-row>

		</el-form>

		<!--收款记录-->
		<el-dialog title="新增收款" :visible="newgetVisible" :append-to-body="true" @close="newgetVisible=false"
			:close-on-click-modal="false" v-drag2anywhere width="950px">
			<el-form :model="newgetData" ref="newgetUI" label-width="100px" :rules="newgetRules">
				<el-row>
					<el-col :span="6">
						<el-form-item label="应收总额:">
							{{format2Number(data.sum_platform,numdigits)}}
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="已收总额:">
							{{format2Number(data.income_rmb,numdigits)}}
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="未收总额:">
							{{format2Number(data.sum_platform-data.income_rmb,numdigits)}}
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="收款时间" prop="date">
							<el-date-picker v-model="newgetData.date" value-format="yyyy-MM-dd" placeholder="收款时间">
							</el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="收款金额" prop="amount">
							<el-input-number v-model="newgetData.amount" style="width:180px" :min="0" :step="0.001"
								:precision="3" :max="data.sum_platform-data.income_rmb" placeholder="收款金额"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="收款备注信息" prop="memo">
							<el-input type="textarea" :rows="3" v-model="newgetData.memo" placeholder="收款备注信息">
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="newgetVisible = false" size="medium">取 消</el-button>
				<el-button type="primary" size="medium" @click="handleSaveNewGetAmount">保 存</el-button>
			</div>
		</el-dialog>


		<!--付款记录-->
		<el-dialog title="新增付款记录" :visible="newpayVisible" :append-to-body="true" @close="newpayVisible=false" v-drag2anywhere
			width="950px" 	:close-on-click-modal="false">

			<el-form :model="newpayData" ref="newpayUI" :rules="newpayRules" label-width="100px">
				<el-row>
					<el-col :span="6">
						<el-form-item label="订单总额:">
							{{format2Number(data.sum_order,numdigits)}}
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="应付总额:">
							{{format2Number(data.sum_sup,numdigits)}} ({{data.suprate*100}}%)
						</el-form-item>
					</el-col>
          <el-col :span="6">
          	<el-form-item label="已付金额:">
          		{{format2Number(data.paid_rmb,numdigits)}}
          	</el-form-item>
          </el-col>
					<el-col :span="6">
						<el-form-item label="未付金额:">
							{{format2Number(data.sum_sup-data.paid_rmb,numdigits)}}
						</el-form-item>
					</el-col>

          <el-col>
            <el-form-item label="合作商:">
              {{data.supname}}
            </el-form-item>
          </el-col>
				</el-row>
				<el-row :gutter="20">
               <el-col :span="8" >
              	<el-form-item label="付款方式" prop="paytype">
              		<el-select v-model="newpayData.paytype" placeholder="请选择" >
                    <el-option label="银行转账" value="银行转账"></el-option>
                    <el-option label="微信" value="微信"></el-option>
                    <el-option label="支付宝" value="支付宝"></el-option>
                    <el-option label="现金" value="现金"></el-option>
                    <el-option label="抵扣" value="抵扣"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                  </el-select>
              	</el-form-item>
              </el-col>

              <el-col :span="16">
                <el-form-item label="" v-if="newpayData.paytype!='银行转账'"></el-form-item>
              	<el-form-item label="收款单位:" label-width="100px" prop="ckitle"  v-if="newpayData.paytype=='银行转账'">
              		<el-select v-model="newpayData.ckitle" style="width: 100%;"  placeholder="请选择收款账户"
              			@change="onCheckoutChaned">
              			<el-option :label="item.title" v-for="(item,index) in checkoutList" :key="item.cktitle"
              				:value="item.cktitle"></el-option>
              		</el-select>
              		<div style="font-size: 12px; color: #999;">
              			<el-row>
              				<el-col :span="10"><b>银行账号</b>: {{newpayData.bankid}}</el-col>
              				<el-col :span="14"><b>开户行</b>：{{newpayData.bankname}}</el-col>
              			</el-row>
              			<span style=""></span>
              		</div>
              	</el-form-item>
              </el-col>
              </el-row>
              <el-row :gutter="20">
               <el-col :span="8">
              	<el-form-item label="付款金额" prop="amount">
              		<el-input-number v-model="newpayData.amount" style="width:100%" :min="0" :step="0.001"
              			:max="data.sum_sup-data.paid_rmb" :precision="3" placeholder="收款金额"></el-input-number>
              	</el-form-item>
              </el-col>
              <el-col  :span="8">
              	<el-form-item label="付款日期" prop="date">
              		<el-date-picker v-model="newpayData.date" style="width: 240px;" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" :default-value="new Date()"
              			placeholder="付款时间">
              		</el-date-picker>
              	</el-form-item>
              </el-col>
              <el-col>
              	<el-form-item label="付款信息" prop="memo">
              		<el-input type="textarea" :rows="3" v-model="newpayData.memo" placeholder="付款备注信息">
              		</el-input>
              	</el-form-item>
              </el-col>
            </el-row>
			</el-form>

			<div slot="footer" class="dialog-footer">
				<el-button @click="newpayVisible = false" size="medium">取 消</el-button>
				<el-button type="primary" size="medium" @click="handleSaveNewPayData">保 存</el-button>
			</div>
		</el-dialog>

	</el-dialog>
</template>

<script>
	export default {

		data() {
			var validatepayamount = (rule, value, callback) => {
				if (value <= 0) {
					callback(new Error("付款金额不能等于0"));
				} else if (value > this.data.sum_sup) {
					callback(new Error("付款金额不能大于折扣总额:" + this.data.sum_sup));
				} else {
					callback();
				}
			};
			return {
        numdigits:2,
				index: -1,
				data: {
					income_rmb: 0,
					paid_rmb: 0
				},
				getlist: [],
				paylist: [],
				dialogVisible: false,
				newgetVisible: false,
				newpayVisible: false,
				newgetData: {
					date:"",
          ouid:'',
					platform: '',
					ordercode: '',
					amount: 0,
					memo: ''

				},
				paidstatus:0,
				newpayData: {
					date:'2022-02-15'
				},
				newgetRules: {
					date: [{
						required: true,
						message: '请填写收款日期',
						trigger: 'blur'
					}],
					amount: [{
						required: true,
						message: '请填写正确金额',
						trigger: 'blur'
					}]

				},
				newpayRules: {
					date: [{
						required: true,
						message: '请填写收款日期',
						trigger: 'blur'
					}],
          paytype:[{
            required:true,
            message:"支付方式必选",
            trigger:'change'
          }],
					amount: [{
						required: true,
						message: '请填写正确金额',
						trigger: 'change'
					}],
					ckitle: [{
						required: true,
						message: '收款账号为必填项',
						trigger: 'change'
					}]
				},
				checkoutList: []
			}
		},
    watch:{
      "newpayData.paytype":function(n,o){
          if(n!="银行转账"){
              this.newpayRules.ckitle=null;
          }else{
             this.newpayRules={
            	date: [{
            		required: true,
            		message: '请填写收款日期',
            		trigger: 'blur'
            	}],
              paytype:[{
                required:true,
                message:"支付方式必选",
                trigger:'change'
              }],
            	amount: [{
            		required: true,
            		message: '请填写正确金额',
            		trigger: 'blur'
            	}],
            	ckitle: [{
            		required: true,
            		message: '收款账号为必填项',
            		trigger: 'blur'
            	}]
            };

          }
          console.log(o,n);
      }
    },
		methods: {
			init(index, data) {
				this.index = index;
				this.data = data;
				this.paidstatus=this.data.paid_status==1? true:false;
				this.loadPaylist();
        this.loadIncomelist();
				this.loadCheckAccount();
			},
			format2Number(value, len) {
				var f = parseFloat(value);
				var f = Math.round(value * 10000) / 10000;
				var s = f.toString();
				var rs = s.indexOf('.');
				if (rs < 0) {
					rs = s.length;
					s += '.';
				}
				while (s.length <= rs + len) {
					s += '0';
				}
				return s;
				return realVal;
			},
      loadIncomelist() {
      	this.axios.post("api/admin/income/list_by_order", {
      		ouid: this.data.ouid
      	}).then((res) => {
      		if (res.status == 200 && res.data.code == 1) {
      			this.getlist = res.data.list;
      		}
      	})
      },
			loadPaylist() {
				this.axios.post("api/admin/payment/list_by_order", {
					ouid: this.data.ouid
				}).then((res) => {
					if (res.status == 200 && res.data.code == 1) {
						this.paylist = res.data.list;
					}
				})
			},
			loadCheckAccount() {
				let params = {
					pagesize: 100,
					curpage: 1,
					supid: this.data.supid
				}
				this.axios.post("api/admin/suppliercheckout/list", params).then(res => {
					if (res.status == 200 && res.data.code == 0) {
						this.checkoutList = res.data.list;
					}
				});
			},
			handleSave() {
				const params = {
					ouid: this.data.ouid,
					income_rmb: this.data.income_rmb,
					income_memo: this.data.income_memo
				}
				this.axios.post("api/admin/income/update_getamount", params).then((res) => {
					if (res.status == 200 && res.data.code == 0) {
						this.$message.success({
							message: res.data.msg,
							duration: 1500,
							showClose: true
						});
						this.$emit("closeHandler", this.index, params);
						this.dialogVisible = false;

					} else {
						this.$message.error({
							message: res.data.msg,
							duration: 1500,
							showClose: true
						});
					}
				})
			},
			handleShowNewGetUI() {
				 var date = new Date()
				    var y = 1900 + date.getYear()
				    var m = '0' + (date.getMonth() + 1)
				    var d = '0' + date.getDate()
				var fdate=y + '-' + m.substring(m.length - 2, m.length) + '-' + d.substring(d.length - 2, d.length)
 				this.newgetData.date = fdate;
				this.newgetData.ouid = this.data.ouid;
				this.newgetData.ordercode = this.data.ordercode;
        this.newgetData.supid=this.data.supid;
        this.newgetData.supname=this.data.supname;
				this.newgetData.amount = this.data.sum_platform - this.data.income_rmb;
        this.newgetData.platformid=this.data.platformid;
				this.newgetData.platform = this.data.platform;
				this.newgetData.memo = "";
				this.newgetVisible = true;
			},
			/**********收款相关变化**********/
			handleSaveNewGetAmount() {
				this.$refs.newgetUI.validate(ok => {
					if (ok) {
            if(this.newpayData.amount<=0){
              this.$message.error("暂无可收款金额!");
              return false;
            }

						this.axios.post("api/admin/income/add", this.newgetData).then((res) => {
							if (res.status == 200 && res.data.code == 1) {
								this.getlist.push(res.data.data);
								this.data.income_rmb = res.data.sum;
								this.$message.success({
									message: "收款成功",
									duration: 1000,
									showClose: true
								});
                this.data.income_status=this.data.income_rmb==this.data.sum_platform? 1:0;
								this.$emit("getamountChangedHandler", this.index, res.data.sum,this.data.income_status);
								this.newgetVisible = false;
							}
						})
					}
				})

			},
			handle_delete_get(index, row) {
				this.axios.post("api/admin/income/remove", {
					id: row.id,
					ouid: row.ouid
				}).then(res => {
					if (res.status == 200 && res.data.code == 1) {
						this.getlist.splice(index, 1);
						this.data.income_rmb = res.data.sum;
            this.data.income_status=parseFloat(this.data.income_rmb+"")==this.data.sum_platform? 1:0;
						this.$emit("getamountChangedHandler", this.index, res.data.sum,this.data.income_status);
					}
				})
			},

			/**************新增付款**************************/
			handleShowNewPayUI() {
				var date = new Date();
				    var y = 1900 + date.getYear();
				    var m = '0' + (date.getMonth() + 1);
				    var d = '0' + date.getDate();
					var h='0'+(date.getHours());
					var f='0'+(date.getMinutes());
					var s='0'+(date.getSeconds());
				var fdate=y + '-' + m.substring(m.length - 2, m.length) + '-' + d.substring(d.length - 2, d.length)+" "+h.substring(h.length-2,h.length)+":"+f.substring(f.length-2,f.length)+":"+s.substring(s.length-2,s.length);

				this.newpayData = {
					ouid: this.data.ouid,
					ordercode: this.data.ordercode,
          platformid:this.data.platformid,
					platform: this.data.platform,
					date: fdate,
          paytype:"微信",
					supid: this.data.supid,
					supname: this.data.supname,
					cktitle: '',
					bankname: '',
					bankid: '',
					amount: this.format2Number(this.data.sum_sup-this.data.paid_rmb,this.numdigits),
					memo: ''
				};
				this.newpayVisible = true;
			},
			onCheckoutChaned(value) {
				var option = this.checkoutList.filter(function(cur, index, a) {
					if (cur.cktitle == value) {
						return cur;
					}
				})[0];
				this.newpayData.cktitle = option.cktitle;
				this.newpayData.bankname = option.bankname;
				this.newpayData.bankid = option.bankid;
			},
			handleSaveNewPayData() {
				this.$refs.newpayUI.validate(ok => {
					if (ok) {

            if(this.newpayData.amount<=0){
              this.$message.error("暂无可付款金额!");
              return false;
            }
            this.newpayData.amount=this.format2Number(this.newpayData.amount,this.numdigits);


						this.axios.post("api/admin/payment/add", this.newpayData).then((res) => {
							if (res.status == 200 && res.data.code == 0) {
								this.$message.success({
									message: "付款成功",
									duration: 1000,
									showClose: true
								});
								this.data.paid_rmb=res.data.sum;
								this.paylist.push(res.data.data);
								this.newpayVisible=false;
								this.$emit("paidamountChangeHandler",this.index, res.data.sum,this.data.paid_status);
							}
						})
					}
				})
			},
			handle_delete_pay(index, row) {
				this.axios.post("api/admin/payment/remove", {
					id: row.id,
					ouid: row.ouid
				}).then(res => {
					if (res.status == 200 && res.data.code == 1) {
						this.paylist.splice(index, 1);
						this.data.paid_rmb = res.data.sum;
						if(res.data.sum==0){
							this.data.paid_status=0;
						}
						this.$emit("paidamountChangeHandler",this.index, res.data.paid_rmb,this.data.paid_status);
					}
				})
			},
			handleSwitchPaidStatus:function(ok){
				      let msg = "是否将付款状态设置为: "+(ok ? '已付款' : '未付款');
				      this.$confirm(msg, '提示', {
				        confirmButtonText: '确定',
				        cancelButtonText: '取消',
				        type: 'warning'
				      }).then( () => {
						  this.axios.post("api/admin/payment/update_paidstatus",{ouid:this.data.ouid,paidstatus:this.paidstatus? 1: 0}).then((res=>{
							  if(res.status==200 && res.data.code==1){
								  this.data.paid_status=this.paidstatus;
								  this.$emit("paidstatusChangeHandler",this.index,this.paidstatus);
							  }
						  }))

				        // 业务逻辑
				      }).catch(()=>{
						  this.paidstatus=!this.paidstatus;
					  })
			}

		}

	}
</script>

<style>
</style>
